<template>
  <div class="inventory-query">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>库存查询</h2>
      <div class="header-actions">
        <el-dropdown>
          <el-button type="primary">
            其它操作 <el-icon><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>导出数据</el-dropdown-item>
              <el-dropdown-item>批量操作</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 时间筛选 -->
    <div class="time-filter">
      <div class="time-filter-header">
        <span class="time-filter-title">时间筛选：</span>
        <span class="time-filter-status">{{ getTimeFilterStatus() }}</span>
      </div>
      
      <el-radio-group v-model="timeFilter" @change="handleTimeFilterChange">
        <el-radio-button label="today">今日</el-radio-button>
        <el-radio-button label="yesterday">昨日</el-radio-button>
        <el-radio-button label="thisWeek">本周</el-radio-button>
        <el-radio-button label="lastWeek">上周</el-radio-button>
        <el-radio-button label="thisMonth">本月</el-radio-button>
        <el-radio-button label="lastMonth">上月</el-radio-button>
        <el-radio-button label="halfYear">最近半年</el-radio-button>
        <el-radio-button label="oneYear">最近一年</el-radio-button>
        <el-radio-button label="custom">自定义时间</el-radio-button>
      </el-radio-group>
      
      <!-- 自定义时间选择器 -->
      <div v-if="timeFilter === 'custom'" class="custom-time">
        <el-date-picker
          v-model="customTimeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleCustomTimeChange"
        />
      </div>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-form">
      <el-form :model="searchForm" :inline="true" label-width="80px">
        <el-form-item label="货品">
          <el-input 
            v-model="searchForm.productName" 
            placeholder="请输入货品名称/编号"
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="货品类型">
          <el-select 
            v-model="searchForm.productTypeId" 
            placeholder="请选择"
            style="width: 150px"
          >
            <el-option label="电子产品" value="电子产品" />
            <el-option label="服装" value="服装" />
            <el-option label="食品" value="食品" />
            <el-option label="日用品" value="日用品" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="单位">
          <el-select 
            v-model="searchForm.unitName" 
            placeholder="请选择"
            style="width: 120px"
          >
            <el-option label="个" value="个" />
            <el-option label="件" value="件" />
            <el-option label="包" value="包" />
            <el-option label="KG" value="KG" />
            <el-option label="瓶" value="瓶" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="仓库名称">
          <el-select 
            v-model="searchForm.inventory" 
            placeholder="请选择"
            style="width: 150px"
          >
            <el-option label="仓库一" value="仓库一" />
            <el-option label="仓库二" value="仓库二" />
            <el-option label="仓库三" value="仓库三" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="货品条码">
          <el-input 
            v-model="searchForm.barcode" 
            placeholder="请输入货品条码"
            style="width: 180px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="searchForm.showDisabled">显示停用商品</el-checkbox>
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="searchForm.filterZeroStock">过滤零库存商品</el-checkbox>
        </el-form-item>
        
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number blue">{{ statistics.currentInventoryCount.toLocaleString() }}</div>
              <div class="stat-label">当前库存数量</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number blue">¥{{ statistics.currentInventoryAmount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }}</div>
              <div class="stat-label">当前库存金额</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number green">{{ statistics.inboundCount.toLocaleString() }}</div>
              <div class="stat-label">入库数量</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number orange">{{ statistics.outboundCount.toLocaleString() }}</div>
              <div class="stat-label">出库数量</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number green">{{ statistics.pendingInbound.toLocaleString() }}</div>
              <div class="stat-label">待入库</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number orange">{{ statistics.pendingOutbound.toLocaleString() }}</div>
              <div class="stat-label">待出库</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 表格操作 -->
    <div class="table-actions">
      <el-button type="primary" @click="handleExport">导出</el-button>
      <el-button @click="handleRefresh">刷新</el-button>
      <el-button type="success" @click="handleRefreshStatistics">刷新统计</el-button>
    </div>
    

    <!-- 数据表格 -->
    <el-card class="data-table">
      <el-table 
        :data="tableData" 
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="index" label="序号" width="60" />
        <el-table-column prop="productNo" label="货品编号" width="120" />
        <el-table-column prop="productName" label="货品名称" width="150" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'danger'">
              {{ scope.row.status ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="productTypeId" label="货品类型" width="100" />
        <el-table-column prop="productModel" label="规格型号" width="100" />
        <el-table-column prop="unitName" label="单位" width="80" />
        <el-table-column prop="barcode" label="条码" width="120" />
        <el-table-column prop="inventory" label="仓库名称" width="120" />
        <el-table-column prop="location" label="库位名称" width="120" />
        <el-table-column prop="batch" label="批次" width="120" />
        <el-table-column prop="current_Inventory" label="当前库存" width="100" />
        <el-table-column prop="totalMoeny" label="库存金额" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="handleInOutFlow(scope.row)">出入库流水</el-button>
            <el-button type="text" @click="handleInventoryDistribution(scope.row)">库存分布</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { TZRead,TZWrite } from '@/http/interceptors'
import { useRouter,useRoute } from 'vue-router'
const router=useRouter();
const route=useRoute();

// 时间筛选
const timeFilter = ref('thisMonth')
const customTimeRange = ref([])

// 搜索表单
const searchForm = reactive({
  productName: '',
  productTypeId: '',
  unitName: '',
  inventory: '',
  barcode: '',
  showDisabled: false,
  filterZeroStock: false
})

// 分页
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 统计数据
const statistics = reactive({
  currentInventoryCount: 0,
  currentInventoryAmount: 0,
  inboundCount: 0,
  outboundCount: 0,
  pendingInbound: 0,
  pendingOutbound: 0
})



// 初始化数据
onMounted(async () => {
  // 初始化统计数据
  await updateStatistics([])
  // 加载数据
  await loadData()
})

// 加载数据
const loadData = async () => {
  loading.value = true
  
  try {
    // 获取时间范围
    const timeRange = getTimeRange()
    
    // 构建查询参数
    const params = {
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize,
      productName: searchForm.productName || undefined,
      productTypeId: searchForm.productTypeId || undefined,
      unitName: searchForm.unitName || undefined,
      inventory: searchForm.inventory || undefined,
      barcode: searchForm.barcode || undefined
    }
    
    // 添加时间筛选参数
    if (timeRange) {
      params.startTime = formatDate(timeRange.startDate)
      params.endTime = formatDate(timeRange.endDate)
      // 同时设置CreateTime参数以兼容现有接口
      params.createTime = formatDate(timeRange.startDate)
    }
    
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === undefined || params[key] === '') {
        delete params[key]
      }
    })
    
    console.log('查询参数:', params)
    
    const res = await TZRead.get("/api/Product/list", { params })
    
    if (res.data.code === 200) {
      // 设置表格数据
      tableData.value = res.data.pageData.map((item, index) => ({
        ...item,
        index: (pagination.pageIndex - 1) * pagination.pageSize + index + 1
      }))
      
      // 设置分页信息
      pagination.total = res.data.totalCount
      
      // 更新统计卡片数据（异步）
      await updateStatistics(res.data.pageData)
      
      ElMessage.success('查询成功')
    } else {
      ElMessage.error(res.data.message || '查询失败')
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取出入库统计数据
const getInOutStatistics = async () => {
  // 获取时间范围用于出入库统计
  const timeRange = getTimeRange()
  
  try {
    // 调用出入库流水接口获取统计数据
    const inoutParams = {
      pageIndex: 1,
      pageSize: 1000, // 获取足够多的数据来统计
      startTime: timeRange ? formatDate(timeRange.startDate) : undefined,
      endTime: timeRange ? formatDate(timeRange.endDate) : undefined
    }
    
    // 移除空值参数
    Object.keys(inoutParams).forEach(key => {
      if (inoutParams[key] === undefined || inoutParams[key] === '') {
        delete inoutParams[key]
      }
    })
    
    console.log('出入库统计查询参数:', inoutParams)
    console.log('当前时间筛选范围:', timeRange ? `${formatDate(timeRange.startDate)} 至 ${formatDate(timeRange.endDate)}` : '无时间筛选')
    
    const inoutRes = await TZRead.get("/api/Product/inout-list", { params: inoutParams })
    
    if (inoutRes.data.code === 200 && inoutRes.data.pageData) {
      const inoutData = inoutRes.data.pageData
      
      // 统计入库数量
      const inboundTotal = inoutData
        .filter(item => item.inOutType === '入库')
        .reduce((sum, item) => sum + (item.inNumber || 0), 0)
      
      // 统计出库数量
      const outboundTotal = inoutData
        .filter(item => item.inOutType === '出库')
        .reduce((sum, item) => sum + (item.outNumbber || 0), 0)
      
      // 更新统计数据
      statistics.inboundCount = inboundTotal
      statistics.outboundCount = outboundTotal
      
      console.log('出入库统计结果:', {
        inboundTotal,
        outboundTotal,
        dataCount: inoutData.length,
        timeRange: timeRange ? `${formatDate(timeRange.startDate)} 至 ${formatDate(timeRange.endDate)}` : '无时间筛选'
      })
      
      // 待入库和待出库数量（这里可以根据实际业务逻辑计算）
      // 暂时使用模拟数据，实际应该从订单或待处理数据中获取
      statistics.pendingInbound = Math.floor(inboundTotal * 0.1) // 模拟：待入库为入库数量的10%
      statistics.pendingOutbound = Math.floor(outboundTotal * 0.15) // 模拟：待出库为出库数量的15%
      
    } else {
      console.warn('出入库统计查询失败:', inoutRes.data.message)
      // 如果查询失败，使用默认值
      statistics.inboundCount = 0
      statistics.outboundCount = 0
      statistics.pendingInbound = 0
      statistics.pendingOutbound = 0
    }
  } catch (error) {
    console.error('获取出入库统计数据失败:', error)
    // 出错时使用默认值
    statistics.inboundCount = 0
    statistics.outboundCount = 0
    statistics.pendingInbound = 0
    statistics.pendingOutbound = 0
  }
}

// 更新统计卡片数据
const updateStatistics = async (data) => {
  if (data && data.length > 0) {
    // 计算当前库存数量
    statistics.currentInventoryCount = data.reduce((sum, item) => sum + (item.current_Inventory || 0), 0)
    // 计算当前库存金额
    statistics.currentInventoryAmount = data.reduce((sum, item) => sum + (item.totalMoeny || 0), 0)
  } else {
    // 重置库存统计数据
    statistics.currentInventoryCount = 0
    statistics.currentInventoryAmount = 0 
  }
  
  // 获取出入库统计数据
  await getInOutStatistics()
}



// 搜索
const handleSearch = async () => {
  console.log('搜索条件:', searchForm)
  pagination.pageIndex = 1
  
  // 搜索时也更新统计数据（基于当前时间筛选）
  await updateStatistics([])
  await loadData()
}

// 时间筛选变化
const handleTimeFilterChange = async (value) => {
  console.log('时间筛选变化:', value)
  pagination.pageIndex = 1
  
  // 立即更新统计数据（基于新的时间筛选）
  await updateStatistics([])
  
  // 然后加载表格数据
  await loadData()
}

// 获取时间范围
const getTimeRange = () => {
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  
  switch (timeFilter.value) {
    case 'today':
      return {
        startDate: today,
        endDate: new Date(today.getTime() + 24 * 60 * 60 * 1000 - 1)
      }
    case 'yesterday':
      const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000)
      return {
        startDate: yesterday,
        endDate: new Date(yesterday.getTime() + 24 * 60 * 60 * 1000 - 1)
      }
    case 'thisWeek':
      const weekStart = new Date(today.getTime() - today.getDay() * 24 * 60 * 60 * 1000)
      return {
        startDate: weekStart,
        endDate: new Date(weekStart.getTime() + 7 * 24 * 60 * 60 * 1000 - 1)
      }
    case 'lastWeek':
      const lastWeekStart = new Date(today.getTime() - (today.getDay() + 7) * 24 * 60 * 60 * 1000)
      return {
        startDate: lastWeekStart,
        endDate: new Date(lastWeekStart.getTime() + 7 * 24 * 60 * 60 * 1000 - 1)
      }
    case 'thisMonth':
      const monthStart = new Date(now.getFullYear(), now.getMonth(), 1)
      return {
        startDate: monthStart,
        endDate: new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59)
      }
    case 'lastMonth':
      const lastMonthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1)
      return {
        startDate: lastMonthStart,
        endDate: new Date(now.getFullYear(), now.getMonth(), 0, 23, 59, 59)
      }
    case 'halfYear':
      const halfYearAgo = new Date(now.getTime() - 6 * 30 * 24 * 60 * 60 * 1000)
      return {
        startDate: halfYearAgo,
        endDate: now
      }
    case 'oneYear':
      const oneYearAgo = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000)
      return {
        startDate: oneYearAgo,
        endDate: now
      }
    case 'custom':
      if (customTimeRange.value && customTimeRange.value.length === 2) {
        return {
          startDate: new Date(customTimeRange.value[0]),
          endDate: new Date(customTimeRange.value[1] + ' 23:59:59')
        }
      }
      return null
    default:
      return null
  }
}

// 格式化日期为ISO字符串
const formatDate = (date) => {
  if (!date) return undefined
  
  // 确保是Date对象
  const dateObj = date instanceof Date ? date : new Date(date)
  
  // 格式化为 YYYY-MM-DD 格式，适合数据库查询
  const year = dateObj.getFullYear()
  const month = String(dateObj.getMonth() + 1).padStart(2, '0')
  const day = String(dateObj.getDate()).padStart(2, '0')
  
  return `${year}-${month}-${day}`
}

// 自定义时间变化处理
const handleCustomTimeChange = async (value) => {
  console.log('自定义时间变化:', value)
  if (value && value.length === 2) {
    // 立即更新统计数据（基于新的时间筛选）
    await updateStatistics([])
    
    // 重置分页并重新加载数据
    pagination.pageIndex = 1
    await loadData()
  }
}

// 获取时间筛选状态描述
const getTimeFilterStatus = () => {
  const timeRange = getTimeRange()
  if (!timeRange) return '未设置时间筛选'
  
  const formatDateStr = (date) => {
    return date.toLocaleDateString('zh-CN')
  }
  
  const startStr = formatDateStr(timeRange.startDate)
  const endStr = formatDateStr(timeRange.endDate)
  
  if (startStr === endStr) {
    return `${startStr}`
  } else {
    return `${startStr} 至 ${endStr}`
  }
}

// 重置
const handleReset = async () => {
  Object.keys(searchForm).forEach(key => {
    if (typeof searchForm[key] === 'boolean') {
      searchForm[key] = false
    } else {
      searchForm[key] = ''
    }
  })
  timeFilter.value = 'thisMonth'
  customTimeRange.value = []
  pagination.pageIndex = 1
  
  // 重置后立即更新统计数据
  await updateStatistics([])
  await loadData()
}

// 导出
const handleExport = () => {
  ElMessage.success('导出功能待实现')
}

// 刷新
const handleRefresh = async () => {
  await loadData()
}

// 刷新统计数据
const handleRefreshStatistics = async () => {
  try {
    await getInOutStatistics()
    ElMessage.success('统计数据已刷新')
  } catch (error) {
    console.error('刷新统计数据失败:', error)
    ElMessage.error('刷新统计数据失败')
  }
}

// 分页大小变化
const handleSizeChange = async (size) => {
  pagination.pageSize = size
  await loadData()
}

// 当前页变化
const handleCurrentChange = async (page) => {
  pagination.pageIndex = page
  await loadData()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 出入库流水
const handleInOutFlow = (row) => {
  console.log('查看出入库流水:', row)
  router.push({
    path: '/inout',
    query: { id: row.id }
  })
}

// 库存分布
const handleInventoryDistribution = (row) => {
  console.log('查看库存分布:', row)
   router.push({
    path: '/InventoryFB',
    query: { id: row.id }
  })
}
</script>

<style scoped>
.inventory-query {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.time-filter {
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.time-filter-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.time-filter-title {
  font-weight: bold;
  color: #333;
  margin-right: 10px;
}

.time-filter-status {
  color: #409eff;
  font-size: 14px;
}

.time-filter .el-radio-group {
  margin-bottom: 10px;
}

.custom-time {
  margin-top: 10px;
  padding: 10px;
  background: white;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.search-form {
  margin-bottom: 20px;
}

.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  border: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-content {
  padding: 10px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-number.blue {
  color: #409eff;
}

.stat-number.green {
  color: #67c23a;
}

.stat-number.orange {
  color: #e6a23c;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.table-actions {
  margin-bottom: 15px;
}

.data-table {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-card__body) {
  padding: 15px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 15px;
  margin-bottom: 10px;
}
</style> 